// 云函数入口文件
const cloud = require('wx-server-sdk')

// 初始化云开发
cloud.init({
  env: 'liucheng-2gmqvcgs50e86304' // 使用指定的云环境
});

// 云函数入口函数
exports.main = async (event, context) => {
  const db = cloud.database()
  const _ = db.command
  const { manufacturerNam } = event
  console.log(manufacturerNam,11222)
  try {
    console.log(`Fetching orders for manufacturer: ${manufacturerNam}`)

    // 查询 Order 表中 manufactor 字段等于 manufacturerNam 的记录
    const ordersRes = await db.collection('Order').where({
      manufactor: manufacturerNam
    }).get()
    console.log(ordersRes,"ordersRes")
    // 检查是否找到订单记录
    if (ordersRes.data.length === 0) {
      console.warn(`No orders found for manufacturer: ${manufacturerNam}`)
      return {
        success: false,
        message: 'No orders found'
      }
    }

    console.log(`Orders fetched successfully for manufacturer: ${manufacturerNam}`)

    const orders = ordersRes.data;
    const today = new Date();

    // 定义计算天数差异的方法
    function calculateDaysDifference(date1, date2) {
      const oneDay = 24 * 60 * 60 * 1000; // 一天的毫秒数
      const firstDate = new Date(date1); // 将第一个日期字符串转换为 Date 对象
      const secondDate = new Date(date2); // 将第二个日期字符串转换为 Date 对象
      return Math.round((secondDate - firstDate) / oneDay); // 计算两个日期之间的天数差异，并四舍五入
    }

    // 计算 expectDeliTime 与当前日期的天数差异，并添加到订单数据中
    orders.forEach(order => {
      const expectDeliTime = new Date(order.expectDeliTime);
      const dayDiff = calculateDaysDifference(today, expectDeliTime); // 计算天数差异
      order.dayDiff = dayDiff;
    });

    // 按照条件进行排序
    const sortedOrders = orders.sort((a, b) => {
      // orderCompleted 等于 no 的在前面
      if (a.orderCompleted === 'no' && b.orderCompleted !== 'no') {
        return -1
      } else if (a.orderCompleted !== 'no' && b.orderCompleted === 'no') {
        return 1
      }

      // 按照 expectDeliTime 的天数差异升序排列
      return a.dayDiff - b.dayDiff;
    });

    console.log('Sorted orders:', sortedOrders)

    // 返回成功结果
    return {
      success: true,
      data: sortedOrders
    }
  } catch (error) {
    console.error('Error occurred:', error.message)
    // 返回错误结果
    return {
      success: false,
      message: 'Error: ' + error.message
    }
  }
}
